package ptumall.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ptumall.dao.UsersDao;
import ptumall.model.Users;

import java.util.Map;

@Service
public class UserService {
    @Autowired
    private UsersDao usersDao;

    public Users findOrCreateUser(String openid, Map<String, Object> userInfo) {
        // 1. 根据 openid 查询用户是否存在
        Users user = usersDao.selectByOpenid(openid);
        if (user != null) {
            // 2. 如果用户存在，更新信息（可选）
            user.setNickname((String) userInfo.get("nickname"));
            user.setAvatar_url((String) userInfo.get("avatar_url"));
            user.setGender((Integer) userInfo.get("gender"));
            usersDao.updateUser(user);
            return user;
        } else {
            // 3. 用户不存在，创建新用户
            Users newUser = new Users();
            newUser.setOpenid(openid);
            newUser.setNickname((String) userInfo.get("nickname"));
            newUser.setAvatar_url((String) userInfo.get("avatar_url"));
            newUser.setGender((Integer) userInfo.get("gender"));
            usersDao.insertUser(newUser);
            return newUser;
        }
    }
}
